<template>
  <div class="body-layout">
    <!--header start-->
    <!-- 顶部导航 begin -->
    <header class="top-header">
      <article class="header-middle"><img src="../assets/images/nav-logo.png"/></article>
    </header>
    <article class="vf-news-box marginTop44">
      <div class="header border-bottom">
        <div class="header-list">
          <ul>
            <li v-for="(item,index) in header" v-stat='{button_type:index+1,extra:item.view_id}'
                @click="clickHeader(index,item)">
              <a :class="index == indexCh ?'active':''" href="javascript:void(0);">{{item.category_name}}</a>
            </li>

          </ul>
        </div>
      </div>
      <!--header end-->
      <!-- 文章列表 -->
      <div class="vf-news index-view_list" ref="indexList">

        <div class="vf-news-list">

          <div v-for="item in list[indexCh]">
            <article class="vf-news-list_con vf-news-list_con-LR  border-bottom"
                     v-if="item.img_list.length < 3">
              <a href="javascript:void(0);" v-stat='{button_type:6,extra:item.view_id}' @click="routeDetail(item)">
                <div class="news-info">
                  <h3 class="title">{{item.view_title}}</h3>
                  <div class="title-tips">
                    <!--<svg class="icon share" aria-hidden="true"><use-->
                    <!--xlink:href="#icon-share"></use></svg>-->
                    <span class="news-scour"><img src="../assets/images/icon-v.png"/>{{item.author_name}}</span>
                    <span class="reply">评论{{item.comment_count}}</span>
                    <span class="pubtime">{{item.publish_time_fmt}}</span>
                  </div>
                </div>
                <div class="news-img">
                  <img v-for="(img,index) in item.img_list"
                       :src="img.url+'?x-oss-process=image/resize,m_fixed,h_100,w_160'" alt="" v-if="index<1">
                </div>
              </a>
            </article>
            <article class="vf-news-list_con vf-news-list_con-three  border-bottom" v-else>
              <a href="javascript:void(0);" v-stat='{button_type:6,extra:item.view_id}' @click="routeDetail(item)">
                <h3 class="title">{{item.view_title}}</h3>
                <div class="news-info">
                  <img v-for="(img,index) in item.img_list"
                       :src="img.url+'?x-oss-process=image/resize,m_fixed,h_100,w_160'" alt="" v-if="index<3">
                </div>
                <div class="title-tips">
                  <span class="news-scour"><img src="../assets/images/icon-v.png"/>{{item.author_name}}</span>
                  <span class="reply">评论{{item.comment_count}}</span>
                  <span class="pubtime">{{item.publish_time_fmt}}</span>
                </div>
              </a>
            </article>
          </div>
          <article class="vf-bottom-tps">

            <div class="vf-bottom-tps_line" v-show="bottomText.length>0">
              <span>{{bottomText}}</span>
            </div>
          </article>

        </div>

      </div>
    </article>

    <Footer type="ch" id="footer"></Footer>
  </div>

</template>

<script>
  import Footer from '@/components/Footer'
  import util from '@/lib/util.js'
  import Bscroll from 'better-scroll'

  export default {
    name: 'Index',
    components: {
      Footer
    },
    data: function () {
      return {
        header: [],
        indexCh: 0,
        list: {},
        stateList: [],
        finishedCatagory: {},//已触底的catagory
        bottomTestList: [],//底部文字集合，不同的分类下面的文字可能是不同的，需要持久化
        bottomText: "",
        sw: true,
        height: 0
      }
    },
    created: function () {
      util.vars.in_time = new Date().getTime();
      this.height = document.documentElement.clientHeight - 140;
      this.ajaxHeader();


    },
    computed: {},
    mounted: function () {
      this.$nextTick(() => {
        window.addEventListener('scroll', this.onScrollPull)
      })
    },
    watch: {
      '$route': function (to, from) {
      }
    },
    methods: {
      // header 数据加载
      ajaxHeader: function () {
        util.ajax.get('/view/category').then((res) => {
          this.header = res.data;
          let list = {};
          let need_init_text = this.bottomTestList.length == 0;
          for (let i = 0; i < res.data.length; i++) {
            list[i] = [];
            if (need_init_text) {
              this.bottomTestList[i] = "";
            }

            util.vars.lastIndex[i] = 0;
          }
          this.list = list;
          this.ajaxList(0);
        });

      },
      // 加载数据列表
      ajaxList: function (index) {
        this.bottomText = this.bottomTestList[index] || "";
        if (this.finishedCatagory[index]) {
          return false;
        }

        let id = this.header[index]['category_id'];
        let last_id = util.vars.lastIndex[index] || 0;
        let that = this;

        util.ajax.get(`/view/category/list?category_id=${id}&last_id=${last_id}`)
          .then((res) => {
              // 数据加载完毕
              this.sw = true;
              let listData = [];
              if (res.code == '1' && res.data) {
                // 取最后一条数据id
                if (res.data.length > 0) {
                  let len = res.data.length - 1;
                  util.vars.lastIndex[index] = res.data[len]['view_id'];

                  let list = res.data.map(item => {
                    listData.push(item['view_id']);
                    return item
                  });

                  //加载评论数据
                  this.ajaxStatistics(res.data, function (articlelist) {
                    //对时间重新刷新
                    articlelist.map(item => {
                      if (item['publish_time']) {
                        item['publish_time_fmt'] = util.formatDate(item['publish_time']);
                      }
                    });

                    if (last_id == 0) {
                      that.list[index] = articlelist;
                    } else {
                      that.list[index] = that.list[index].concat(articlelist);
                    }

                  });
                }

                if (res.data.length < 10) {
                  this.finishedCatagory[index] = true;
                  //如果第一页就加载完毕，则不显示文字
                  if (last_id === 0) {
                    this.bottomTestList[index] = "";
                  } else {
                    this.bottomTestList[index] = "您太勤奋了，没有更多了";
                  }
                } else {
                  this.bottomTestList[index] = "加载中";
                }
                this.bottomText = this.bottomTestList[index];
              }
            }
          )
      },
      ajaxStatistics: function (articlelist, callback) {
        if (articlelist && articlelist.length > 0) {
          let articleIds = [], list = articlelist.map(item => {
            articleIds.push(item['view_id']);
            return item
          });

          let that = this;
          util.ajax.get(`view/statistics/list?view_id_list=${articleIds}`).then((res) => {
            //这里需要变更对应个文章列表才能出发评论数更新
            if (res.code == 1) {
              let statisList = res.data || [];

              that.stateList = that.stateList.concat(statisList);

              statisList.forEach((item, index) => {
                let ai = articleIds.indexOf(item.view_id);
                if (ai > -1) {
                  list[ai]["comment_count"] = that.commentCount(item.view_id);
                }
              });

              if (typeof callback === "function") {
                callback(list);
              }
            }
          });
        }
      }
      ,
      // header点击
      clickHeader: function (index, item) {
        this.indexCh = index;
        // 点击数据从新加载
        util.vars.lastIndex[index] = 0;
        //切换分类之后，需要把对应的开关清空
        this.finishedCatagory[index] = false;
        this.stateList = [];
        this.ajaxList(index);

      }
      ,
      commentCount: function (id) {
        let count = this.stateList.find((item) => {
          item.comment_amount = item.comment_amount > 10000 ? `${item.comment_amount}`.substring(0, 1) + '万+' : item.comment_amount;
          return item.view_id == id ? true : false
        });
        return count ? count['comment_amount'] : "";
      }
      ,
      routeDetail: function (item) {
        this.$router.push({path: '/pages/Detail', query: {id: item.view_id}});
      },

      onScrollPull(e) {
        if (this.$el.querySelector('.vf-news')) {


          let innerHeight = this.$el.querySelector('.vf-news').clientHeight;

          let bottomHeight = this.$el.querySelector('.vf-bottom-tps').clientHeight;
          let footerHeight = this.$el.querySelector('#footer').clientHeight;
          let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

          if (innerHeight <= scrollTop + document.documentElement.clientHeight - footerHeight) {
            if (this.sw == true) {
              // 将开关关闭
              this.sw = false;
              this.ajaxList(this.indexCh);
            }
          }
        }
      },
    }
  }
</script>
<style scoped>
  /*新的*/
  /* .vf-news {
     overflow: auto;
   }*/
  .vf-bottom-tps {
    width: 80%;
    padding: 0px !important;
  }

</style>


